<template>
  <div class="scene-editor-container">
    <n-card class="scene-card">
      <template #header>
        <div class="card-header">
          <h1>场景编辑器</h1>
          <div class="header-actions">
            <n-button @click="saveScene" type="primary">
              <template #icon><n-icon><SaveOutline /></n-icon></template>
              保存场景
            </n-button>
            <n-button @click="goBack">
              <template #icon><n-icon><ArrowBackOutline /></n-icon></template>
              返回
            </n-button>
          </div>
        </div>
      </template>
      
      <div class="content-layout">
        <div class="scene-canvas-container">
          <div class="canvas-header">
            <n-space>
              <n-select
                v-model:value="currentTool"
                :options="toolOptions"
                size="small"
                style="width: 120px"
              />
              <n-button-group size="small">
                <n-button @click="zoomIn"><n-icon><AddOutline /></n-icon></n-button>
                <n-button @click="zoomOut"><n-icon><RemoveOutline /></n-icon></n-button>
                <n-button @click="resetZoom"><n-icon><RefreshOutline /></n-icon></n-button>
              </n-button-group>
            </n-space>
          </div>
          
          <div class="scene-canvas" ref="canvasRef">
            <!-- 场景画布将在这里渲染 -->
            <div class="canvas-placeholder">
              <n-empty description="场景画布加载中...">
                <template #extra>
                  <n-button @click="initCanvas">重新加载</n-button>
                </template>
              </n-empty>
            </div>
          </div>
          
          <div class="canvas-footer">
            <n-space justify="space-between">
              <span>缩放: {{ Math.round(zoomLevel * 100) }}%</span>
              <span>分辨率: {{ canvasWidth }} x {{ canvasHeight }}</span>
            </n-space>
          </div>
        </div>
        
        <div class="scene-controls">
          <n-tabs type="line" animated>
            <n-tab-pane name="elements" tab="场景元素">
              <div class="tab-content">
                <h3>场景元素</h3>
                <n-scrollbar style="max-height: 500px" :x-scrollable="false">
                  <n-collapse>
                    <n-collapse-item title="背景" name="backgrounds">
                      <n-grid :cols="2" :x-gap="12" :y-gap="12">
                        <n-grid-item v-for="bg in backgrounds" :key="bg.id">
                          <div class="element-item" @click="addElement(bg)">
                            <img :src="bg.thumbnail" :alt="bg.name" />
                            <span>{{ bg.name }}</span>
                          </div>
                        </n-grid-item>
                      </n-grid>
                    </n-collapse-item>
                    
                    <n-collapse-item title="角色" name="characters">
                      <n-grid :cols="2" :x-gap="12" :y-gap="12">
                        <n-grid-item v-for="char in characters" :key="char.id">
                          <div class="element-item" @click="addElement(char)">
                            <img :src="char.thumbnail" :alt="char.name" />
                            <span>{{ char.name }}</span>
                          </div>
                        </n-grid-item>
                      </n-grid>
                    </n-collapse-item>
                    
                    <n-collapse-item title="道具" name="props">
                      <n-grid :cols="2" :x-gap="12" :y-gap="12">
                        <n-grid-item v-for="prop in props" :key="prop.id">
                          <div class="element-item" @click="addElement(prop)">
                            <img :src="prop.thumbnail" :alt="prop.name" />
                            <span>{{ prop.name }}</span>
                          </div>
                        </n-grid-item>
                      </n-grid>
                    </n-collapse-item>
                  </n-collapse>
                </n-scrollbar>
              </div>
            </n-tab-pane>
            
            <n-tab-pane name="properties" tab="属性">
              <div class="tab-content">
                <template v-if="selectedElement">
                  <h3>{{ selectedElement.name }} 属性</h3>
                  
                  <n-form
                    :model="elementProperties"
                    label-placement="left"
                    label-width="80"
                    require-mark-placement="right-hanging"
                    size="small"
                  >
                    <n-form-item label="位置 X">
                      <n-input-number
                        v-model:value="elementProperties.x"
                        size="small"
                        @update:value="updateElementProperty('x', $event)"
                      />
                    </n-form-item>
                    
                    <n-form-item label="位置 Y">
                      <n-input-number
                        v-model:value="elementProperties.y"
                        size="small"
                        @update:value="updateElementProperty('y', $event)"
                      />
                    </n-form-item>
                    
                    <n-form-item label="缩放">
                      <n-input-number
                        v-model:value="elementProperties.scale"
                        size="small"
                        :step="0.1"
                        @update:value="updateElementProperty('scale', $event)"
                      />
                    </n-form-item>
                    
                    <n-form-item label="旋转">
                      <n-input-number
                        v-model:value="elementProperties.rotation"
                        size="small"
                        @update:value="updateElementProperty('rotation', $event)"
                      />
                    </n-form-item>
                    
                    <n-form-item label="透明度">
                      <n-slider
                        v-model:value="elementProperties.opacity"
                        :step="0.01"
                        :min="0"
                        :max="1"
                        @update:value="updateElementProperty('opacity', $event)"
                      />
                    </n-form-item>
                    
                    <n-form-item label="图层">
                      <n-input-number
                        v-model:value="elementProperties.zIndex"
                        size="small"
                        @update:value="updateElementProperty('zIndex', $event)"
                      />
                    </n-form-item>
                  </n-form>
                  
                  <n-divider />
                  
                  <n-space justify="end">
                    <n-button size="small" @click="deleteElement">
                      <template #icon><n-icon><TrashOutline /></n-icon></template>
                      删除元素
                    </n-button>
                    <n-button size="small" @click="duplicateElement">
                      <template #icon><n-icon><CopyOutline /></n-icon></template>
                      复制元素
                    </n-button>
                  </n-space>
                </template>
                <n-empty v-else description="请选择一个场景元素" />
              </div>
            </n-tab-pane>
            
            <n-tab-pane name="layers" tab="图层">
              <div class="tab-content">
                <h3>场景图层</h3>
                <n-scrollbar style="max-height: 500px" :x-scrollable="false">
                  <n-list>
                    <n-list-item v-for="layer in sceneElements" :key="layer.id">
                      <n-thing
                        :title="layer.name"
                        :description="`类型: ${layer.type}`"
                        @click="selectElement(layer)"
                      >
                        <template #avatar>
                          <div class="layer-thumbnail">
                            <img :src="layer.thumbnail" :alt="layer.name" />
                          </div>
                        </template>
                        <template #header-extra>
                          <n-space>
                            <n-switch
                              v-model:value="layer.visible"
                              size="small"
                              @update:value="toggleLayerVisibility(layer)"
                            />
                            <n-dropdown
                              :options="layerActions"
                              @select="handleLayerAction($event, layer)"
                            >
                              <n-button size="small">
                                <n-icon><EllipsisVerticalOutline /></n-icon>
                              </n-button>
                            </n-dropdown>
                          </n-space>
                        </template>
                      </n-thing>
                    </n-list-item>
                  </n-list>
                </n-scrollbar>
              </div>
            </n-tab-pane>
          </n-tabs>
        </div>
      </div>
    </n-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import {
  NCard,
  NButton,
  NButtonGroup,
  NIcon,
  NSpace,
  NTabs,
  NTabPane,
  NSelect,
  NCollapse,
  NCollapseItem,
  NGrid,
  NGridItem,
  NForm,
  NFormItem,
  NInputNumber,
  NSlider,
  NDivider,
  NList,
  NListItem,
  NThing,
  NSwitch,
  NDropdown,
  NEmpty,
  NScrollbar
} from 'naive-ui'
import {
  SaveOutline,
  ArrowBackOutline,
  AddOutline,
  RemoveOutline,
  RefreshOutline,
  TrashOutline,
  CopyOutline,
  EllipsisVerticalOutline
} from '@vicons/ionicons5'

const router = useRouter()
const message = useMessage()

// 画布引用和状态
const canvasRef = ref<HTMLElement | null>(null)
const zoomLevel = ref(1)
const canvasWidth = ref(1280)
const canvasHeight = ref(720)

// 工具和选项
const currentTool = ref('select')
const toolOptions = [
  { label: '选择', value: 'select' },
  { label: '移动', value: 'move' },
  { label: '缩放', value: 'scale' },
  { label: '旋转', value: 'rotate' }
]

// 选中的元素和属性
const selectedElement = ref<any>(null)
const elementProperties = reactive({
  x: 0,
  y: 0,
  scale: 1,
  rotation: 0,
  opacity: 1,
  zIndex: 0
})

// 场景元素
const sceneElements = ref<any[]>([])

// 图层操作
const layerActions = [
  { label: '上移一层', key: 'moveUp' },
  { label: '下移一层', key: 'moveDown' },
  { label: '置于顶层', key: 'moveToTop' },
  { label: '置于底层', key: 'moveToBottom' },
  { label: '删除', key: 'delete' }
]

// 模拟数据
const backgrounds = ref([
  { id: 'bg1', name: '城市街道', type: 'background', thumbnail: 'https://picsum.photos/id/1015/100/60' },
  { id: 'bg2', name: '森林', type: 'background', thumbnail: 'https://picsum.photos/id/1018/100/60' },
  { id: 'bg3', name: '海滩', type: 'background', thumbnail: 'https://picsum.photos/id/1019/100/60' },
  { id: 'bg4', name: '山脉', type: 'background', thumbnail: 'https://picsum.photos/id/1021/100/60' }
])

const characters = ref([
  { id: 'char1', name: '角色 A', type: 'character', thumbnail: 'https://picsum.photos/id/1025/100/60' },
  { id: 'char2', name: '角色 B', type: 'character', thumbnail: 'https://picsum.photos/id/1027/100/60' }
])

const props = ref([
  { id: 'prop1', name: '桌子', type: 'prop', thumbnail: 'https://picsum.photos/id/1056/100/60' },
  { id: 'prop2', name: '椅子', type: 'prop', thumbnail: 'https://picsum.photos/id/1059/100/60' },
  { id: 'prop3', name: '灯', type: 'prop', thumbnail: 'https://picsum.photos/id/1060/100/60' }
])

// 初始化画布
const initCanvas = () => {
  message.success('画布初始化成功')
  // 实际项目中，这里会初始化画布，可能使用 Canvas API、WebGL 或第三方库如 Pixi.js
}

// 缩放控制
const zoomIn = () => {
  zoomLevel.value = Math.min(zoomLevel.value + 0.1, 3)
}

const zoomOut = () => {
  zoomLevel.value = Math.max(zoomLevel.value - 0.1, 0.3)
}

const resetZoom = () => {
  zoomLevel.value = 1
}

// 元素操作
const addElement = (element: any) => {
  const newElement = {
    ...element,
    id: `element-${Date.now()}`,
    x: canvasWidth.value / 2,
    y: canvasHeight.value / 2,
    scale: 1,
    rotation: 0,
    opacity: 1,
    zIndex: sceneElements.value.length,
    visible: true
  }
  
  sceneElements.value.push(newElement)
  selectElement(newElement)
  message.success(`添加了 ${element.name}`)
}

const selectElement = (element: any) => {
  selectedElement.value = element
  
  // 更新属性面板
  elementProperties.x = element.x
  elementProperties.y = element.y
  elementProperties.scale = element.scale
  elementProperties.rotation = element.rotation
  elementProperties.opacity = element.opacity
  elementProperties.zIndex = element.zIndex
}

const updateElementProperty = (property: string, value: any) => {
  if (selectedElement.value) {
    selectedElement.value[property] = value
    
    // 在实际项目中，这里会更新画布中的元素
  }
}

const deleteElement = () => {
  if (selectedElement.value) {
    const index = sceneElements.value.findIndex(el => el.id === selectedElement.value.id)
    if (index !== -1) {
      sceneElements.value.splice(index, 1)
      selectedElement.value = null
      message.success('元素已删除')
    }
  }
}

const duplicateElement = () => {
  if (selectedElement.value) {
    const duplicate = {
      ...selectedElement.value,
      id: `element-${Date.now()}`,
      x: selectedElement.value.x + 20,
      y: selectedElement.value.y + 20
    }
    
    sceneElements.value.push(duplicate)
    selectElement(duplicate)
    message.success('元素已复制')
  }
}

// 图层操作
const toggleLayerVisibility = (layer: any) => {
  layer.visible = !layer.visible
  // 在实际项目中，这里会更新画布中的元素可见性
}

const handleLayerAction = (action: string, layer: any) => {
  const index = sceneElements.value.findIndex(el => el.id === layer.id)
  if (index === -1) return
  
  switch (action) {
    case 'moveUp':
      if (index < sceneElements.value.length - 1) {
        const temp = sceneElements.value[index + 1]
        sceneElements.value[index + 1] = sceneElements.value[index]
        sceneElements.value[index] = temp
        updateLayerZIndices()
      }
      break
      
    case 'moveDown':
      if (index > 0) {
        const temp = sceneElements.value[index - 1]
        sceneElements.value[index - 1] = sceneElements.value[index]
        sceneElements.value[index] = temp
        updateLayerZIndices()
      }
      break
      
    case 'moveToTop':
      const element = sceneElements.value.splice(index, 1)[0]
      sceneElements.value.push(element)
      updateLayerZIndices()
      break
      
    case 'moveToBottom':
      const elem = sceneElements.value.splice(index, 1)[0]
      sceneElements.value.unshift(elem)
      updateLayerZIndices()
      break
      
    case 'delete':
      deleteElement()
      break
  }
}

const updateLayerZIndices = () => {
  sceneElements.value.forEach((element, idx) => {
    element.zIndex = idx
    if (selectedElement.value && element.id === selectedElement.value.id) {
      elementProperties.zIndex = idx
    }
  })
}

// 保存场景
const saveScene = () => {
  message.success('场景已保存')
  // 在实际项目中，这里会调用 API 保存场景数据
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 生命周期钩子
onMounted(() => {
  initCanvas()
})

onBeforeUnmount(() => {
  // 清理资源
})
</script>

<style lang="scss" scoped>
.scene-editor-container {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
  
  .scene-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      h1 {
        margin: 0;
        font-size: 24px;
        font-weight: 500;
      }
      
      .header-actions {
        display: flex;
        gap: 12px;
      }
    }
  }
  
  .content-layout {
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: 20px;
    margin-top: 20px;
    
    .scene-canvas-container {
      border: 1px solid var(--border-color);
      border-radius: 4px;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      
      .canvas-header {
        padding: 8px;
        border-bottom: 1px solid var(--border-color);
        background-color: var(--card-color);
      }
      
      .scene-canvas {
        flex-grow: 1;
        background-color: #1e1e1e;
        position: relative;
        min-height: 500px;
        
        .canvas-placeholder {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
      
      .canvas-footer {
        padding: 8px;
        border-top: 1px solid var(--border-color);
        background-color: var(--card-color);
        font-size: 12px;
        color: var(--text-color-secondary);
      }
    }
    
    .scene-controls {
      border: 1px solid var(--border-color);
      border-radius: 4px;
      overflow: hidden;
      
      .tab-content {
        padding: 16px;
        
        h3 {
          margin-top: 0;
          margin-bottom: 16px;
          font-size: 16px;
        }
      }
      
      .element-item {
        border: 1px solid var(--border-color);
        border-radius: 4px;
        overflow: hidden;
        cursor: pointer;
        transition: transform 0.2s, box-shadow 0.2s;
        
        img {
          width: 100%;
          height: 60px;
          object-fit: cover;
        }
        
        span {
          display: block;
          padding: 4px 8px;
          font-size: 12px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        
        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
      }
      
      .layer-thumbnail {
        width: 40px;
        height: 40px;
        overflow: hidden;
        border-radius: 4px;
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }
    }
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .scene-editor-container {
    padding: 10px;
    
    .content-layout {
      grid-template-columns: 1fr;
      
      .scene-controls {
        margin-top: 20px;
      }
    }
  }
}
</style> 